package com.just521.xinshoutong;

import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.feedback.UMFeedbackService;
import com.just521.xinshoutong.database.NoteDBCtrl;
import com.just521.xinshoutong.database.NoteDBCtrl.DBAccessListener;
import com.just521.xinshoutong.database.NoteDBCtrl.DBRequestParam;
import com.just521.xinshoutong.json.MainList_SummaryRec;
import com.just521.xinshoutong.json.Note_Detail;
import com.just521.xinshoutong.json.ToDo;
import com.just521.xinshoutong.view.CRemindInfo;
import com.just521.xinshoutong.view.NoteElePlugin;
import com.just521.xinshoutong.view.NoteTextView;
import com.just521.xinshoutong.view.ReminderView;
import com.just521.xinshoutong.view.TagsView;
import com.just521.xinshoutong.view.ToDoView;

public class Activity_note extends ActivityBase implements OnClickListener,
DBAccessListener{
	
	Note_Detail mnotedetail=new Note_Detail();
	byte[] mlock=new byte[0];
	LinearLayout mContentContainer;
	View mtoastNeedDelete;
	NoteElePlugin mcurplug;
	MainList_SummaryRec msummary=new MainList_SummaryRec();
	
	NoteDBCtrl db=new NoteDBCtrl();
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.note);
		long lnotifydate=0;
		Intent it=getIntent();
		if(it!=null){
			MainList_SummaryRec summary=(MainList_SummaryRec)it.getSerializableExtra("summary");
			if(summary==null){
				
			}else{
				msummary=summary;
				DBRequestParam param=db.getRequestParam();
				param.listener=this;
				param.task="getNoteDetailByUUID";
				db.getNoteDetailByUUID_Local(param, summary.getUuid());
			}
			lnotifydate=it.getLongExtra("date", -1);
		}
		mtoastNeedDelete=findViewById(R.id.note_content_toast);
		mtoastNeedDelete.setOnClickListener(this);
		mContentContainer=(LinearLayout)findViewById(R.id.note_container);
//		mContentContainer.removeView(tv);
		Button btn=(Button)findViewById(R.id.note_tool_text);
		btn.setOnClickListener(this);
		btn=(Button)findViewById(R.id.note_tool_todo);
		btn.setOnClickListener(this);
		btn=(Button)findViewById(R.id.note_tool_remind);
		btn.setOnClickListener(this);
		btn=(Button)findViewById(R.id.note_tool_tags);
		btn.setOnClickListener(this);
		if(lnotifydate!=-1){
			addTodoPlug(null);
		}
	}
	
	protected void onActivityResult(int requestCode, int resultCode,  
            Intent data){ 
		super.onActivityResult(requestCode, resultCode, data);
		if(mtoastNeedDelete!=null){
			mContentContainer.removeView(mtoastNeedDelete);
		}
		switch (requestCode){  
			case NoteTextView.FLAG_TO_EDIT_TEXT:
			
				if(data!=null){
					processTextCommit(data);
				}
				break;
			case ReminderView.FLAG_TO_EDIT_REMIND:  
				
				CRemindInfo	clTemp	=	( CRemindInfo )data.getSerializableExtra( "remindinfo" );
				
				mcurplug.initData(clTemp);
				break;
			
		}  
	}
	private void processTextCommit(Intent data){
		
		mcurplug.initData(data.getStringExtra("notetext"));
//		int sourceid=data.getIntExtra("sourceid",-1);
//		if(sourceid!=-1){
//			IdentifyContent idc=new IdentifyContent();
//			idc.setId(sourceid);
//			idc.setContent(data.getStringExtra("notetext"));
//			Map<String,IdentifyContent> node=new HashMap<String, IdentifyContent>();
//			node.put("text", idc);
//			mnotedetail.editItem(node);
//			updateTextView(idc);
//		}else{
//			
//			int curid=mnotedetail.getMaxID("text");
//			IdentifyContent idc=new IdentifyContent();
//			idc.setId(curid);
//			idc.setContent(data.getStringExtra("notetext"));
//			Map<String,IdentifyContent> node=new HashMap<String, IdentifyContent>();
//			node.put("text", idc);
//			mnotedetail.addItem(node);
//			if(mtoastNeedDelete!=null){
//				mContentContainer.removeView(mtoastNeedDelete);
//			}
//			mContentContainer.addView(getTextView(idc));
//		}
	}
//	private void updateTextView(IdentifyContent idc){
//		int count=mContentContainer.getChildCount();
//		for(int i=0;i<count;i++){
//			View v=mContentContainer.getChildAt(i);
//			if(v.getClass()==TextView.class){
//				IdentifyContent tempidc=(IdentifyContent)v.getTag();
//				if(tempidc.getId()==idc.getId()){
//					v.setTag(idc);
//					((TextView)v).setText(idc.getContent());
//					break;
//				}
//			}
//		}
//	}
//	private View getTextView(final IdentifyContent idc){
//		TextView v=new TextView(this);
//		
//		v.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
//		v.setText(idc.getContent());
//		v.setBackgroundResource(R.drawable.text_field_bg);
//		v.setPadding(10, 10, 10, 10);
//		v.setTag(idc);
//		v.setOnClickListener(new OnClickListener() {
//			
//			@Override
//			public void onClick(View v) {
//				IdentifyContent idctemp=(IdentifyContent)v.getTag();
//				// TODO Auto-generated method stub
//				toTextEditActivity(idc);
//			}
//		});
//		return v;
//	}
	protected void onDestroy() {
		super.onDestroy();
		
	}
	protected void onResume() {
		super.onResume();
		hidekeyboard();
	}
	private void hidekeyboard(){
		int count=mContentContainer.getChildCount();
		InputMethodManager imm=((InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE));
		for(int i=0;i<count;i++){
			try{
				
				((NoteElePlugin)mContentContainer.getChildAt(i)).hideSoftInput();
			}catch(ClassCastException e){
				
			}
		}
	}
	@Override
	public void onClick(View v) {
		switch(v.getId()){
//		case R.id.main_setting:
//			do_main_setting();
//			break;
		case R.id.note_content_toast:
		case R.id.note_tool_text:
			NoteElePlugin notetext=addTextPlug(null);
			mcurplug=notetext;
			notetext.showEditView();
			break;
		case R.id.note_tool_todo:
			NoteElePlugin plugtodo=addTodoPlug(null);
			mcurplug=plugtodo;
			break;
		case R.id.note_tool_remind:
			NoteElePlugin rview=addTodoPlug(null);
			mcurplug=rview;
			break;
		case R.id.note_tool_tags:
			NoteElePlugin tagview=addTagPlug(null);
			mcurplug=tagview;
			tagview.showEditView();
			break;
		default:
			break;
		}	
	}
	private NoteElePlugin addTextPlug(Object ob){
		final NoteTextView notetext=new NoteTextView(this);
		notetext.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
		if(ob==null){
			
			notetext.initData(null);
		}else{
			notetext.orignalData(ob);
			notetext.initData(ob);
		}
		notetext.setActivity(this);
		mContentContainer.addView(notetext);
		notetext.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				notetext.showEditView();
			}
		});
		
		return notetext;
	}
	private NoteElePlugin addTagPlug(Object ob){
		final TagsView tagsview=new TagsView(this);
		tagsview.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
		if(ob==null){
			
			tagsview.initData(null);
		}else{
			tagsview.orignalData(ob);
			tagsview.initData(ob);
		}
		tagsview.setActivity(this);
		mContentContainer.addView(tagsview);
		tagsview.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				tagsview.showEditView();
			}
		});
		
		return tagsview;
	}
	private NoteElePlugin addTodoPlug(Object ob){
		if(mtoastNeedDelete!=null){
			mContentContainer.removeView(mtoastNeedDelete);
			mtoastNeedDelete=null;
		}
		ToDoView plugtodo= new ToDoView(this);
		plugtodo.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
		if(ob==null){
			
			plugtodo.initData(null);
		}else{
			plugtodo.orignalData(ob);
			plugtodo.initData(ob);
		}
		mContentContainer.addView(plugtodo);
		return plugtodo;
	}
	private NoteElePlugin addRemindPlug(Object ob){
		if(mtoastNeedDelete!=null){
			mContentContainer.removeView(mtoastNeedDelete);
			mtoastNeedDelete=null;
		}
		ReminderView rview= new ReminderView(this);
		rview.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
		rview.initData(null);
		mContentContainer.addView(rview);
		return rview;
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		do{
			
			if ((keyCode == KeyEvent.KEYCODE_BACK)) {
				if(!isDataChanged()){
					break;
				}
				//init detail from views
				initDetailFromViews();
				//save note
				String notejson="";
				
				
				long time=System.currentTimeMillis();
				
				msummary.setModifytime(time);
//			summary.setNotifytime(notifytime);
				msummary.setSummary(mnotedetail.getSummary());
				int status=-1;
				if(msummary.isBishavenotify() || msummary.isBishavetodo()){
					status=0;
				}
				msummary.setStatus(status);
				
				DBRequestParam param=db.getRequestParam();
				param.listener=this;
				
				mnotedetail.setModifytime(time);
				
				if(mnotedetail.getUuid()==null ||mnotedetail.getUuid().length()==0){
					param.task="addNote";
					msummary.setCreatetime(time);
					mnotedetail.setCreatetime(time);
					notejson=JSON.toJSONString(mnotedetail);
					String summaryjson=JSON.toJSONString(msummary);
					String uuid=java.util.UUID.randomUUID().toString();
					db.addNote_Local(param, notejson, summaryjson,uuid);
				}else{
					param.task="updateNote";
					notejson=JSON.toJSONString(mnotedetail);
					String summaryjson=JSON.toJSONString(msummary);
					String uuid=mnotedetail.getUuid();
					db.modifyNote_Local(param, notejson, summaryjson,uuid);
				}
			} 
		}while(false);
        return super.onKeyDown(keyCode, event); 
    }
	void initDetailFromViews(){
		mnotedetail=new Note_Detail();
		int count=mContentContainer.getChildCount();
		for(int i=0; i<count; i++){
			NoteElePlugin plug=(NoteElePlugin)mContentContainer.getChildAt(i);
			mnotedetail.addItem(plug.getViewType(),plug.getData());
		}
	}
	boolean isDataChanged(){
		boolean b=false;
		int count=mContentContainer.getChildCount();
		for(int i=0; i<count; i++){
			try{
				
				NoteElePlugin plug=(NoteElePlugin)mContentContainer.getChildAt(i);
				b=plug.isDataChanged();
				if(b){
					break;
				}
			}catch(ClassCastException e){
				
			}
		}
		return b;
	}
	void do_main_setting(){
	
	}

	void do_main_region(){
	
	}

	void do_main_nearby(){
	
	}

	void do_main_feedback(){
		UMFeedbackService.openUmengFeedbackSDK(this);
	}
	
	
	public void onDBSuccess(DBRequestParam param){
		if(param.task.equals("getNoteDetailByUUID")){
			Note_Detail tempdetail=JSON.parseObject(param.rstjson, Note_Detail.class);
			List<Map<String,Object>> itemlist=tempdetail.getItems();
			if(itemlist==null || itemlist.size()==0 ){
				return;
			}
			if(mtoastNeedDelete!=null){
				mContentContainer.removeView(mtoastNeedDelete);
				mtoastNeedDelete=null;
			}
			for(Map<String,Object> item:itemlist){
				Object ob=item.get("text");
				if(ob!=null){
					addTextPlug(ob);
				}
				ob=item.get("todo");
				if(ob!=null){
					JSONObject job=(JSONObject)ob;
					Object todo=JSON.parseObject(job.toJSONString(), ToDo.class);
					addTodoPlug(todo);
				}
				ob=item.get("notify");
				if(ob!=null){
					addRemindPlug(ob);
				}
			}
//			hidekeyboard();
		}
		
	}
	public void onDBError(DBRequestParam param){
		
	}
	
	
	
	
	
	
	
	

}

